cmake_minimum_required(VERSION 3.20)
if(CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR)
    project(Assertor LANGUAGES CXX)
endif()
include(GNUInstallDirs)

option(ASSERTOR_ENABLE_ASSERTS "Enable asserts support if available" ON)
option(ASSERTOR_ENABLE_STACKTRACE "Enable stacktrace support if available" ON)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

if(NOT TARGET assertor)
    add_library(assertor INTERFACE)
    target_compile_features(assertor INTERFACE cxx_std_17)
endif()
if(NOT TARGET assertor::assertor)
    add_library(assertor::assertor ALIAS assertor)
endif()
target_include_directories(assertor INTERFACE
    $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
    $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>
)

if(NOT TARGET logstream)
    add_subdirectory(contrib/logstream)
endif()
target_link_libraries(assertor INTERFACE logstream::logstream)

# Detect asserts support (macro only; impl gated by ASSERTOR_USE_*_IMPL)
if(ASSERTOR_ENABLE_ASSERTS)
    target_compile_definitions(assertor INTERFACE ASSERTOR_ENABLE_ASSERTS=1)
endif()

# Detect stacktrace support (macro only; impl gated by ASSERTOR_USE_*_IMPL)
if(ASSERTOR_ENABLE_STACKTRACE)
    target_compile_definitions(assertor INTERFACE ASSERTOR_ENABLE_STACKTRACE=1)
    if(UNIX AND NOT APPLE)
        # dladdr 需要链接 libdl；-rdynamic 导出可执行符号便于 dladdr 解析
        target_link_libraries(assertor INTERFACE dl)
        target_link_options(assertor INTERFACE -rdynamic)
    endif()
endif()

# Examples
function(add_example target_name source_relpath)
    add_executable(${target_name} ${source_relpath})
    target_link_libraries(${target_name} PRIVATE assertor)
    set_target_properties(${target_name} PROPERTIES 
        CXX_STANDARD 17
        CXX_STANDARD_REQUIRED YES
    )
endfunction()

add_example(assertor_full_api_showcase examples/full_api_showcase.cpp)
add_example(assertor_context_showcase examples/context_showcase.cpp)

# Custom target to run all examples
add_custom_target(run_assertor_examples
    COMMENT "Running all assertor examples"
    COMMAND echo "=== Running assertor_full_api_showcase ==="
    COMMAND ${CMAKE_COMMAND} -E env ASSERTOR_LOG_FILE=${CMAKE_CURRENT_BINARY_DIR}/kp.log $<TARGET_FILE:assertor_full_api_showcase>
    COMMAND echo "=== Running assertor_context_showcase ==="
    COMMAND ${CMAKE_COMMAND} -E env ASSERTOR_LOG_FILE=${CMAKE_CURRENT_BINARY_DIR}/context_showcase.log $<TARGET_FILE:assertor_context_showcase>
    DEPENDS 
        assertor_full_api_showcase
        assertor_context_showcase
    WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
)

# install headers and library within contrib
install(TARGETS assertor EXPORT AssertorTargets)
install(DIRECTORY include/ DESTINATION include)
install(EXPORT AssertorTargets
    FILE assertorTargets.cmake
    NAMESPACE assertor::
    DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/assertor
)
